//
//  MTCreateLiveView.m
//  MeToo
//
//  Created by 俊松何 on 2018/7/21.
//  Copyright © 2018年 tianxie. All rights reserved.
//

#import "MTCreateLiveView.h"
#import "UIView+ViewController.h"
#import "MLLinkLabel.h"
#import "MTWebViewController.h"

@interface MTCreateLiveView ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIPickerViewDelegate,UIPickerViewDataSource>
@property (weak, nonatomic) IBOutlet UILabel *liveTitleLable;
@property (weak, nonatomic) IBOutlet UITextField *titletextField;
@property (weak, nonatomic) IBOutlet UILabel *covertitleLable;
@property (weak, nonatomic) IBOutlet UIImageView *coverImageView;
@property (weak, nonatomic) IBOutlet UIButton *createButton;

@property (nonatomic,copy) NSString *coverUrl;
@property(nonatomic,strong) UIImage *selectImage;

@property (weak, nonatomic) IBOutlet UIView *bgView;

@property(nonatomic,strong) MLLinkLabel *protoclLabel;
@property (weak, nonatomic) IBOutlet UIView *bottomView;

//直播分类背景view
@property (weak, nonatomic) IBOutlet UIView *catryBgView;


@property (weak, nonatomic) IBOutlet UIView *pickBgView;

@property (weak, nonatomic) IBOutlet UIPickerView *pickView;

@property (weak, nonatomic) IBOutlet UILabel *categoryLable;

@property(nonatomic,strong) NSMutableArray *types;

@property(nonatomic,strong) MTLiveTypeModel *selectType;


@end



@implementation MTCreateLiveView

+(instancetype)createLiveView
{
    MTCreateLiveView *view  = [[NSBundle mainBundle] loadNibNamed:@"MTCreateLiveView" owner:nil options:nil].lastObject;
    view.frame = CGRectMake(0, 0, WIDTH, HEIGHT);
    return view;
}

-(void)awakeFromNib
{
    [super awakeFromNib];
    _bgView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.2];
    
    _catryBgView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.2];
    
    _createButton.layer.masksToBounds = YES;
    _createButton.layer.cornerRadius = 22;
    UITapGestureRecognizer *gester = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeKeyBoardClick)];
    [_bottomView addGestureRecognizer:gester];
    self.coverUrl = [LTClient sharedClient].currentUser.avatar;
    [self.coverImageView sd_setImageWithURL:[NSURL URLWithString:self.coverUrl] placeholderImage:defaultImgae];
    
    
    self.protoclLabel = [MLLinkLabel new];
    self.protoclLabel.textAlignment = NSTextAlignmentCenter;
    NSString* protocolStr = [NSString stringWithFormat:@"%@《%@》",NSLTLocalizedString(@"live.loginMeans", nil), NSLTLocalizedString(@"login.aggree", nil)];
    NSString* aggreementStr = [NSString stringWithFormat:@"《%@》", NSLTLocalizedString(@"live.aggree", nil)];
    self.protoclLabel.textColor = [UIColor whiteColor];
    self.protoclLabel.numberOfLines = 2;
    self.protoclLabel.font = [UIFont systemFontOfSize:12];
    NSMutableAttributedString* attString= [[NSMutableAttributedString alloc]initWithString:protocolStr];
    [attString setAttributes:@{NSForegroundColorAttributeName : mainTintColor, NSLinkAttributeName : @"asdsd"} range:[protocolStr rangeOfString:aggreementStr]];
    self.protoclLabel.attributedText = attString;
    @weakify(self);
    [self.protoclLabel setDidClickLinkBlock:^(MLLink *link, NSString *linkText, MLLinkLabel *label) {
        @strongify(self);
        [self protolClicked];
    }];
    
//    [self addSubview:self.protoclLabel];
    
    [self insertSubview:self.protoclLabel belowSubview:self.pickBgView];
    
    [self.protoclLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.createButton.mas_left).offset(0);
        make.top.mas_equalTo(self.createButton.mas_bottom).offset(20);
        make.right.mas_equalTo(self.createButton.mas_right).offset(0);
    }];
    
    self.pickView.delegate = self;
    self.pickView.dataSource = self;
    self.pickView.userInteractionEnabled = YES;
    self.pickBgView.hidden = YES;
    
    [[MTLiveApiManager manager] getliveTypesWithcompletion:^(NSMutableArray<MTLiveTypeModel *> *types, MTError *error) {
       if(error == nil)
       {
           self.types = types;
           [self.pickView reloadAllComponents];
       }
        
    }];
    
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return self.types.count;
}
- (nullable NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    MTLiveTypeModel *model = self.types[row];
    
    return model.name;
}

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    NSLog(@"%ld",row);
}

-(void)protolClicked
{
    MTWebViewController *webVc = [[MTWebViewController alloc] init];
    webVc.url = @"http://mitu_static.108usd.com/live-protocol";
    [self.currentViewController.navigationController pushViewController:webVc animated:YES];
}


- (IBAction)createClick:(UIButton *)sender {
    
    self.createButton.userInteractionEnabled = NO;
    [[MTLiveApiManager manager] createLiveWithTitle:self.titletextField.text cover:self.coverUrl topics:@"" typeId:self.selectType.id completion:^(MTLiveModel *liveModel, MTError *error) {
         self.createButton.userInteractionEnabled = YES;
        if(error == nil)
        {
            if([self.delegate respondsToSelector:@selector(createLiveView:liveModel:)])
            {
                [self.delegate createLiveView:self liveModel:liveModel];
            }
        }else
        {
            [MBProgressHUD showMessage:error.errorDescription];
        }
    }];
}
- (IBAction)closeClick:(UIButton *)sender {
    if([self.delegate respondsToSelector:@selector(createLiveViewClose:)])
    {
        [self.delegate createLiveViewClose:self];
    }
}



- (IBAction)setCoverClick:(UIButton *)sender {
    
    [self pushTZImagePickerController];
    return;
    
    UIAlertController *alterVc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:NSLTLocalizedString(@"personInfo.takePhoto", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self takePhoto];
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:NSLTLocalizedString(@"personInfo.selectPhoto", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self pushTZImagePickerController];
    }];
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:NSLTLocalizedString(@"main.cancle", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alterVc addAction:action1];
    [alterVc addAction:action2];
    [alterVc addAction:action3];
    [self.currentViewController presentViewController:alterVc animated:YES completion:nil];
}



-(void)uploadCoverImage
{
    NSData *data = UIImageJPEGRepresentation(self.selectImage, 0.1);
    [MBProgressHUD showProcessHud:nil toView:self];
    [[MTHttpTool shareTool] uploadImageData:data progress:^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
    } success:^(NSString *fileUrl, LTFileTokenModel *model) {
        [MBProgressHUD hideHUDForView:self];
        self.coverUrl = fileUrl;
    } failer:^(MTError *lterror) {
        [MBProgressHUD hideHUDForView:self];
        [MBProgressHUD showError:lterror.errorDescription];
    }];
}


#pragma mark - 照相
- (void)takePhoto {
    
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    [self.currentViewController presentViewController:picker animated:YES completion:^{
        
    }];
    
    
}

- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *originalimage = [info objectForKey:UIImagePickerControllerOriginalImage];
    UIImage *editImage = [info objectForKey:UIImagePickerControllerEditedImage];
    if(editImage != nil)
    {
        self.selectImage = editImage;
    }else
    {
        self.selectImage = originalimage;
    }
    [self uploadCoverImage];
    self.coverImageView.image = self.selectImage;
}

-(void)closeKeyBoardClick
{
    [self.titletextField resignFirstResponder];
}

#pragma mark - 选择图片
- (void)pushTZImagePickerController {
    
    
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self.currentViewController presentViewController:picker animated:YES completion:^{
    }];
}

- (IBAction)selectCategoryClick:(UIButton *)sender {
    
    self.pickBgView.hidden = NO;
    
}

- (IBAction)selectOkClick:(UIButton *)sender {
    
    self.pickBgView.hidden = YES;
    NSInteger row = [self.pickView selectedRowInComponent:0];
    
    MTLiveTypeModel *model = self.types[row];
    self.selectType = model;
    self.categoryLable.text = model.name;

    // do something
}

- (IBAction)cancleClick:(UIButton *)sender {
    self.pickBgView.hidden = YES;
}
- (IBAction)beautyClick:(UIButton *)sender {
    
    if(self.delegate && [self.delegate respondsToSelector:@selector(createLiveViewbeautyClick)])
    {
        [self.delegate createLiveViewbeautyClick];
    }
}



@end
